package com.caius.xiaohashu.data.align.job;

import cn.hutool.core.collection.CollUtil;
import com.caius.xiaohashu.data.align.constant.RedisKeyConstant;
import com.caius.xiaohashu.data.align.constant.TableConstants;
import com.caius.xiaohashu.data.align.domain.mapper.DeleteMapper;
import com.caius.xiaohashu.data.align.domain.mapper.SelectMapper;
import com.caius.xiaohashu.data.align.domain.mapper.UpdateMapper;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author Caius
 * @description
 * @since Created in 2025-05-30
 */
@Component
@Slf4j
public class FollowingCountShardingXxlJob {

    @Resource
    private SelectMapper selectMapper;
    @Resource
    private UpdateMapper updateMapper;
    @Resource
    private DeleteMapper deleteMapper;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @XxlJob("followingCountShardingJobHandler")
    public void followingCountShardingJobHandler() throws Exception {
        int shardIndex = XxlJobHelper.getShardIndex();
        int shardTotal = XxlJobHelper.getShardTotal();

        XxlJobHelper.log("=================> 开始定时分片广播任务：对当日发生变更的用户关注数进行对齐");
        XxlJobHelper.log("分片参数：当前分片序号 = {}, 总分片数 = {}", shardIndex, shardTotal);

        log.info("分片参数：当前分片序号 = {}, 总分片数 = {}", shardIndex, shardTotal);

        String date = LocalDate.now()
                .format(DateTimeFormatter.ofPattern("yyyyMMdd"));

        String tableNameSuffix = TableConstants.buildTableNameSuffix(date, (long) shardIndex);

        int batchSize = 1000;

        int processedTotal = 0;

        for(;;) {
            // 1. 分批次查询 t_data_align_following_count_temp_日期_分片序号，如一批次查询 1000 条，直到全部查询完成
            List<Long> userIds = selectMapper.selectBatchFromDataAlignFollowingCountTempTable(tableNameSuffix, batchSize);

            if (CollUtil.isEmpty(userIds)) break;

            // 2: 循环这一批发生变更的用户 ID， 对 t_following 关注表执行 count(*) 操作，获取总数
            userIds.forEach(userId -> {
                int followingTotal = selectMapper.selectCountFromFollowingTableByUserId(userId);

                // 3: 更新 t_user_count 表，并更新对应 Redis 缓存
                int count = updateMapper.updateUserFollowingTotalByUserId(userId, followingTotal);
                // 更新对应 Redis 缓存
                if (count > 0) {
                    String redisKey = RedisKeyConstant.buildCountUserKey(userId);
                    Boolean hasKey = redisTemplate.hasKey(redisKey);
                    if (hasKey) {
                        redisTemplate.opsForHash().put(redisKey, RedisKeyConstant.FIELD_FOLLOWING_TOTAL, followingTotal);
                    }
                }
            });

            // 4. 批量物理删除这一批次记录
            deleteMapper.batchDeleteDataAlignFollowingCountTempTable(tableNameSuffix, userIds);

            // 当前处理的数量
            processedTotal += userIds.size();
        }
        XxlJobHelper.log("=================> 结束定时分片广播任务：对当日发生变更的用户关注数进行对齐，共对齐记录数：{}", processedTotal);
    }
}
